package com.cms.exception;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.cms.util.Formater;;
public class ExceptionPrint {
	private static final ExceptionPrint exceptionPrint = new ExceptionPrint();

	public static ExceptionPrint getInstance() {
		return exceptionPrint;
	}

	private ExecutorService executor;
	private BlockingQueue<ExceptionInfo> queue;
	private boolean isReady;

	private ExceptionPrint() {
		try {
			queue = new ArrayBlockingQueue<ExceptionInfo>(50);
			executor = Executors.newSingleThreadExecutor();
			executor.execute(new PrintTask(queue));
			isReady = true;
		} catch (FileNotFoundException e) {
			isReady = false;
			queue = null;
			if (executor != null)
				executor.shutdownNow();
			e.printStackTrace();
		}
	}

	public void print(ExceptionInfo exceptionInfo) {
		if (isReady == false) {
			throw new RuntimeException("存在错误！");
		}
		try {
			queue.put(exceptionInfo);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	// 将其放入tomcat/bin/exceptionLog.log目录下
	private static class PrintTask implements Runnable {
		private PrintStream log;
		// private PrintWriter log;
		private BlockingQueue<ExceptionInfo> queue;

		private PrintTask(BlockingQueue<ExceptionInfo> queue) throws FileNotFoundException {
			log = System.out;
			// new PrintWriter("exceptionLog.log");
			this.queue = queue;
			if (this.queue == null) {
				throw new RuntimeException("缓存队列为空！");
			}
			;
		}

		public void run() {
			try {
				while (!Thread.interrupted()) {
					printSingleException(queue.take());
					// 尝试性质的获取4个，以便flush时打印尽可能多的信息，提高性能
					printSingleException(queue.poll());
					printSingleException(queue.poll());
					printSingleException(queue.poll());
					printSingleException(queue.poll());
					// log.flush();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		private void printSingleException(ExceptionInfo exceptionInfo) {
			if (exceptionInfo == null)
				return;
			StringBuilder sb = new StringBuilder();
			sb.append("异常ID：").append(exceptionInfo.getId()).append(";").append("\n").append("用户名：").append(exceptionInfo.getUser()).append(";")
					.append("\n").append("时间：").append(Formater.formatDateTime(exceptionInfo.getDate())).append(";").append("\n").append("调试信息：")
					.append(exceptionInfo.getExtDebugInfo()).append(";").append("\n").append("异常栈信息：").append(exceptionInfo.getStackDesc())
					.append(";").append("\n");
			log.println(sb);
		}

		// 将其存入数据对应表中，暂未实现
		private void print2Db(ExceptionInfo exceptionInfo) {
		}
	}
}
